#include <my_header.h>

/* Usage: ./1_socket_client */
int main(void){                                  

    // 服务器的IP地址
    char *sourceIp = "192.168.229.128";
    char *sourcePort = "8080";

    // 初始化Socket:  调用Socket函数创建一个Socket通信端点
    int socketFd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(socketFd, -1, "socket");

    // 方式一：inet_addr
    // 把 点分十进制, 转成in_addr_t类型(网络IP),  把其存储到结构体in_addr类型中
   // in_addr_t addrIp = inet_addr(sourceIp);
   // struct in_addr inAddr;
   // inAddr.s_addr = addrIp;
    
    // 方式二：inet_aton
    struct in_addr inAddr;
    inet_aton(sourceIp, &inAddr);

    // 把端口转为int类型
    int sourcePortInt = atoi(sourcePort);
    // 把端口号；由字节主序，转为网络字序
    int sourcePortNext = htons(sourcePortInt);
    // int sourcePortInt = htons(atoi(sourcePort));
    
    // 构建struct sockaddr 类型
    struct sockaddr_in socketAddr;
    socketAddr.sin_family = AF_INET;
    socketAddr.sin_port = sourcePortNext;
    socketAddr.sin_addr = inAddr;

    //客户端向服务端发起建立连接请求
    int res_connect = connect(socketFd, (struct sockaddr *)&socketAddr,sizeof(socketAddr));
    ERROR_CHECK(res_connect, -1, "connect");

    while(1)
    {
        char buf[60] = { 0 };

        // 读取标准输入
        read(STDIN_FILENO, buf, sizeof(buf)-1);
    
        // 把标准输入发送给服务器
        int res_send = send(socketFd, buf, sizeof(buf),0);
        ERROR_CHECK(res_send, -1, "send");

        char buf2[60] = { 0 };
        // 读取对方输入
        int res_recv = recv(socketFd, buf2, sizeof(buf2), 0);
        ERROR_CHECK(res_recv, -1, "res_recv");  // 读取失败
        ERROR_CHECK(res_recv, 0, "other close");    // 连接已关闭

        // 打印标准输出
        write(STDOUT_FILENO, buf2, sizeof(buf2));

    }
    close(socketFd);


    return 0;
}


